<?php


namespace Proj\ResManBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Proj\ResmanBundle\Helper\GenerationHelper;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\HttpFoundation\Request;

use Proj\ResManBundle\Entity\Project;
use Proj\ResManBundle\Entity\Activity;
use Proj\ResManBundle\Entity\Department;
use Proj\ResManBundle\Form\ProjectsType;
use Proj\ResManBundle\Form\ActivityType;

/**
 * @Route("/department")
 */
class DepartmentController extends Controller
{
     /**
     * @Route("/")
     */
    public function indexAction()
    {
        return array();
    }
    
    /**
     * @Route("/projects", name="department_get_projects")
     */
    public function projectsAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->get('security.context')->getToken()->getUser();
        $persoana = $user->getPerson();
        
        $projects = $em->getRepository('ProjResManBundle:Project')->findByPerson($persoana);

        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Department:department_get_projects.html.twig',
            array('projects' => $projects, 
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
        
    }
    
    /**
     * @Route("/projects/all", name="department_projects_all")
     */
    public function projectsAllAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->get('security.context')->getToken()->getUser();
        $persoana = $user->getPerson();
        
        $projects = $em->getRepository('ProjResManBundle:Project')->findBy(array('department' => $persoana->getDepartment()));

        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Department:department_projects_all.html.twig',
            array('projects' => $projects, 
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
    /**
     * @Route("/projects/add_activity/{id}", name="department_add_activity")
     */
    public function addActivityAction($id) {
        $request = $this->getRequest();
        $em = $this->getDoctrine()->getManager();
        
        $project = $em->getRepository('ProjResManBundle:Project')->find($id);
        
        $activity = new Activity();
        $form = $this->createForm(new ActivityType(), $activity);
        $dateError = false;
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            
            if ($form->isValid()) {
                date_default_timezone_set('Europe/Bucharest');
                $activity->setCreationDate(new \DateTime());
                $activity->setApproved(false);
                $activity->setProject($project);
                
                if ($activity->getStartDate() > $activity->getEndDate()) {
                    $dateError = true;
                }
                
                if (!$dateError) {
                    $em->persist($activity);
                    $em->flush();

                    $this->get('session')->getFlashBag()->add('activity-notice', 'Activitatea a fost adaugata cu succes.');
                
                    return $this->redirect($this->generateUrl('department_add_activity', array('id' => $id)));
                }
            }
        }
        
        return $this->render(
            'ProjResManBundle:Department:department_add_activity.html.twig',
            array('form' => $form->createView(),
                'dateError' => $dateError,
                'projectId' => $id,
                'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
     /**
     * @Route("/calendar", name="department_get_tasks")
     */
    public function tasksCalendarAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $request = $this->getRequest();
        $user = $this->get('security.context')->getToken()->getUser();
        $personalTasks = new ArrayCollection();
        $persoana = $user->getPerson();
        $projectId = $request->query->get('project_id');
        $tasks= null;
        if ($projectId == Null){
            $tasks = $em->getRepository('ProjResManBundle:Task')->findByPerson($persoana);
        }
        else{
            $project = $em->getRepository('ProjResManBundle:Project')->find($projectId);
            $tasks = $em->getRepository('ProjResManBundle:Task')->findByPersonProject($persoana, $project);
        }
        
        usort($tasks,array($this, 'cmp'));
        
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        return $this->render(
            'ProjResManBundle:Department:department_tasks_calendar.html.twig',
            array('tasks' => $tasks, 
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
        
    }
    
    /**
     * @Route("/projects/add", name="department_projects_add")
     */
    public function projectsAddAction() {
        
        $project = new Project();
        $user = $this->get('security.context')->getToken()->getUser();
        $persoana = $user->getPerson();
        $departament = $persoana->getDepartment();
        $form = $this->createForm(new ProjectsType(), $project);
        $request = $this->getRequest();       
        $dateError = false;      
        
        $baseurl = $request->getScheme() . '://' . $request->getHttpHost() . $request->getBasePath() . "/app_dev.php";
        $content_array = array("submenu" => $this->getLinksArray($baseurl));
        
        if ($request->getMethod() == 'POST') {
            $form->bindRequest($request);
            if ($form->isValid()) {
                date_default_timezone_set('Europe/Bucharest');
                $project->setCreationDate(new \DateTime());
                $project->setState('0');
                $project->setDepartment($departament);
                $em = $this->getDoctrine()->getManager();
                $project->setApproved(false);
                if ($project->getStartDate() > $project->getEndDate()) {
                    $dateError = true;
                }
                
                if (!$dateError) {
                    $em->persist($project);
                    $em->flush();

                    $this->get('session')->getFlashBag()->add('proj-notice', 'Proiectul a fost adaugat cu succes.');
                
                    return $this->redirect($this->generateUrl('department_projects_add'));
                }
            }
        }
        
        return $this->render(
            'ProjResManBundle:Department:projects_add.html.twig',
            array('form' => $form->createView(),
                   'dateError' => $dateError,
                  'template_content' => $this->getTemplateContent($baseurl, $content_array)
            )
        );
    }
    
    function cmp($a, $b)
    {
        if ($a->getStartDate() == $b->getStartDate())
            return 0;
        if ($a->getStartDate() < $b->getStartDate())
            return -1;
        return 0;
    }
    
    
     private function getTemplateContent($baseurl, $content_array) {
        
        $securityContext = $this->container->get('security.context');
        $token = $securityContext->getToken();
        $user = $token->getUser();
        $roles = "";

        $menu = array(
            "public" => "$baseurl/public/index",
            "admin" => "$baseurl/admin/index",
            "director" => "$baseurl/director/index",
            "cadre" => "$baseurl/cadre/index",
            "login" => "$baseurl/login",
            "logout" => "$baseurl/logout",
        );

        $text = array(
            "login" => "Log-in",
            "logout" => "Log-out",
        );

        $auth = array(
            "user" => $user,
            "isAuth" => $securityContext->isGranted('IS_AUTHENTICATED_REMEMBERED'),
            "roles" => $roles
        );

        $header_content = array(
            "menu" => $menu,
            "text" => $text
        );

        $template_content = array(
            "header" => $header_content,
            "content" => $content_array,
            "footer" => array(),
            "auth" => $auth
        );
        
        return $template_content;
    }
    
    private function getLinksArray($baseurl){
        return array (
            1 => array("href" => "$baseurl/department/projects", 
                       "title" => "Proiecte",
                       "title_desc" => "Proiecte proprii"),
            2 => array("href" => "$baseurl/department/calendar", 
                       "title" => "Calendar",
                       "title_desc" => "Calendar task-uri")
        );
    }

}
?>
